<?php
require('./includes/config.inc.php');
$page_title = 'Forgot your Password?';
include('./includes/header.html');
require(MYSQL);
$pass_errors = array();

// Validate the email address
if($_SERVER['REQUEST_METHOD'] == 'POST')	{
	if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))	{
		$q = 'SELECT id FROM shop_member WHERE email = "'.	mysqli_real_escape_string($dbc, $_POST['email'])	.'"';
		$r = mysqli_query($dbc, $q);
		if(mysqli_num_rows($r) == 1)	{	// Retrieve the user ID
			list($uid) = mysqli_fetch_array($r, MYSQLI_NUM);
		} else {	// No database match made
			$pass_errors['email'] = 'The submitted email address does not match those on file!';
		}
	} else {	// No valid address submitted.
		$pass_errors['email'] = 'Please enter a valid email address!';
	} // End of $_POST['email'] IF
	
	// Generate a new password
	if(empty($pass_errors))	{	// If everything's OK
		$p = substr(md5(uniqid(rand(), true)), 10, 15);
	
		// Add the new password to the database;
		
		$q = "UPDATE shop_member SET pass ='".	get_password_hash($q)	."'WHERE id = $uid LIMIT 1";	
		$r = mysqli_query($dbc, $q);
		if(mysqli_affected_rows($dbc) == 1)	{	// If it ran OK
			// Send the new password to the member
			$body = "Your password to log into <http://www.cetylene07.cafe24.com/se2-team3-shop> has been temporarily changed to '$p'. Please log in using that password and this email address. Then you may change your password to something more familar.";
			mail($_POST['email'], 'Your temporary password.', $body, 'From:admin_shop@gamil.com');
			echo '<h3> Your password has been changed.</h3><p>You will receive the new, temporary password via email. Once you have logged in with this new password, you may change it by clicking on the "Change password" link.</p>';
			include('./includes/footer.html');
			exit();
		} else {	//If it did not run OK
			trigger_error('Your password could not be changed due to a system error. We apologize for any inconvenience.');
		}
	
	}	// End of $uid IF
} // End of the main Submit conditional


//Create form
require('./includes/form_functions.inc.php');
?><h3>Reset Your Password</h3>
<p>Enter your email address below to reset your password.</p>
<form action="forgot_password.php" method="post" accept-charset="utf-8">
<p><label for="email"><strong>Email Address</strong></label><br />
<?php 
create_form_input('email', 'text', $pass_errors); ?></p>
<input type="submit" name="submit_button" value="Reset &rarr;" id="submit_button" class="formbutton" />
</form>

<?php
include('./includes/footer.html');
?>